window.onload=function(){

    //创建ajax异步访问后台
    //使用async简化Generator
    async function gen() {
        //调用代码块fetch("data.json") 返回一个Promise对象
        let response = await fetch("http://127.0.0.1:3000/");
        //await等待，等上一个代码块执行完毕再执行 返回一个Promise对象
        let data = await response.json();   
        return data;
    }
    let res = gen(); 
    console.log(res);
    res.then(
        (result) =>{
            var fu = document.getElementById("sj");
            for(let item of result){
                console.log(item);
                var tr = document.createElement("tr");
                tr.innerHTML=`<tr>
                                <td>${item.xh}</td>
                                <td>${item.xm}</td>
                                <td>${item.nj}</td>
                            </tr>`;
                fu.appendChild(tr);            
            }
        }
    ).catch(
        (error)=>{
            console.log(error);
        }
    );

    //查询按钮点击事件
    document.getElementById("search").onclick=function(){
       //获取条件
       let xm = document.getElementById("xm").value;
       let nj = document.getElementById("nj").value;
       //使用async简化Generator
        async function gen() {
            //调用代码块fetch("data.json") 返回一个Promise对象
            let response = await fetch("http://127.0.0.1:3000/?xm="+xm+"&nj="+nj);
            //await等待，等上一个代码块执行完毕再执行 返回一个Promise对象
            let data = await response.json();   
            return data;
        }
        let res = gen(); 
        console.log(res);
        res.then(
            (result) =>{
                //清除数据
                var fu = document.getElementById("sj");
                fu.innerHTML = "";

                for(let item of result){
                    console.log(item);
                    var tr = document.createElement("tr");
                    tr.innerHTML=`<tr>
                                    <td>${item.xh}</td>
                                    <td>${item.xm}</td>
                                    <td>${item.nj}</td>
                                </tr>`;
                    fu.appendChild(tr);            
                }
            }
        ).catch(
            (error)=>{
                console.log(error);
            }
        );
    }
}

function url_encode(url){
    url = encodeURIComponent(url);
    url = url.replace(/%3A/g, ":");
    url = url.replace(/%2F/g, "/");
    url = url.replace(/%3F/g, "?");
    url = url.replace(/%3D/g, "=");
    url = url.replace(/%26/g, "&");
    
    return url;
 }